package cn.getech.data.metadata.service.impl;

import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.metadata.entity.CollectionNotificationReceived;
import cn.getech.data.metadata.entity.CollectionNotificationUser;
import cn.getech.data.metadata.entity.meta.CollectionTask;
import cn.getech.data.metadata.mapper.CollectionNotificationUserMapper;
import cn.getech.data.metadata.model.req.change.CollectionNotificationUserReq;
import cn.getech.data.metadata.model.res.CollectionNotificationUserListRes;
import cn.getech.data.metadata.service.CollectionNotificationReceivedService;
import cn.getech.data.metadata.service.CollectionNotificationUserGroupService;
import cn.getech.system.center.entity.SysUserEntity;
import cn.getech.system.center.model.res.UserListRes;
import cn.getech.system.center.service.SysTenantService;
import cn.getech.system.center.service.SysUserService;
import cn.getech.system.center.utils.ShiroUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service("collectionNotificationService")
public class CollectionNotificationUserGroupGroupServiceImpl extends ServiceImpl<CollectionNotificationUserMapper, CollectionNotificationUser>   implements CollectionNotificationUserGroupService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysTenantService sysTenantService;

    @Autowired
    private CollectionNotificationUserMapper  collectionNotificationUserMapper;

    @Autowired
    private CollectionNotificationReceivedService CollectionNotificationReceivedServiceImpl;

    @Override
    public IPage<CollectionNotificationUserListRes> listBy(CollectionNotificationUserReq req) {
        IPage<CollectionNotificationUserListRes>listResIPage = new Page<CollectionNotificationUserListRes>();
        LambdaQueryWrapper<CollectionNotificationUser> lambdaQuery = Wrappers.lambdaQuery();
        //租户过滤
        lambdaQuery.eq(CollectionNotificationUser::getTenantId,ShiroUtils.getTenantId());
        //用户组查询
        if(StringUtils.isNotBlank(req.getUserGroupName())){
            lambdaQuery.like(CollectionNotificationUser::getUserGroupName,req.getUserGroupName());
        }
        if(StringUtils.isNotBlank(req.getUserEmail())){
            //用户名 或者邮箱查询
            List<CollectionNotificationReceived> collectionNotificationReceiveds = CollectionNotificationReceivedServiceImpl.queryByUserOremail(req.getUserEmail());
            if(CollectionUtils.isNotEmpty(collectionNotificationReceiveds)){
                List<Long> collect = collectionNotificationReceiveds.stream().map(x -> x.getNotificationUserId()).collect(Collectors.toList());
                lambdaQuery.in(CollectionNotificationUser::getId,collect);
            }else {
                lambdaQuery.in(CollectionNotificationUser::getId,0);
            }
        }
        //查询数据
        lambdaQuery.orderByDesc(CollectionNotificationUser::getUpdateTime);
        IPage<CollectionNotificationUser> page = this.page(new Page<>(req.getCurrent(), req.getSize()), lambdaQuery);
        List<CollectionNotificationUser> records = page.getRecords();
        ArrayList<CollectionNotificationUserListRes> arrayList=new ArrayList();
        //转换所需要格式的数据
        records.forEach(x -> {
            UserListRes info = sysUserService.info(x.getCreateUser());
            CollectionNotificationUserListRes collectionNotificationUserListRes = new CollectionNotificationUserListRes();
            BeanUtils.copyProperties(x,collectionNotificationUserListRes);
            List<CollectionNotificationReceived> collectionNotificationReceiveds = CollectionNotificationReceivedServiceImpl.queryByNotificationUserId(x.getId());
            collectionNotificationUserListRes.setCollectionNotificationReceivedList(collectionNotificationReceiveds);
            collectionNotificationUserListRes.setCreateUser(info.getUsername());
            arrayList.add(collectionNotificationUserListRes);
        });
        //添加分页数据
        listResIPage.setRecords(arrayList);
        listResIPage.setPages(page.getPages());
        listResIPage.setCurrent(page.getCurrent());
        listResIPage.setTotal(page.getTotal());
        return listResIPage;
    }

    @Override
    public List<CollectionNotificationUser> getByIds(List<Long> ids) {
        ArrayList<CollectionNotificationUser>  collectionNotificationUsers=new ArrayList<>();
        if(CollectionUtils.isNotEmpty(ids)){
             for(Long id:ids){
                 collectionNotificationUsers.add(this.getById(id));
             }
         }
        return collectionNotificationUsers;
    }

    @Override
    public CollectionNotificationUser getCollectionNotificationUserByid(Long id) {
        CollectionNotificationUser collectionNotificationUser = this.baseMapper.selectById(id);
        if(collectionNotificationUser!=null){
            List<CollectionNotificationReceived> collectionNotificationReceiveds = CollectionNotificationReceivedServiceImpl.queryByNotificationUserId(id);
            collectionNotificationUser.setCollectionNotificationReceiveds(collectionNotificationReceiveds);
            return collectionNotificationUser;
        }
       return null;
    }

    @Override
    @Transactional
    public void udateNotification(CollectionNotificationUser collectionNotificationUser) {
        collectionNotificationUser.setUpdateTime(new Date());
        this.baseMapper.updateById(collectionNotificationUser);
    }


    @Override
    @Transactional
    public void add(CollectionNotificationUser req) {
        checkDate(req,"save");
        //保存通知用户组信息
        CollectionNotificationUser collectionNotificationUser = new CollectionNotificationUser();
        BeanUtils.copyProperties(req,collectionNotificationUser);
        collectionNotificationUser.setCreateUser(ShiroUtils.getUserId());
        collectionNotificationUser.setTenantId(ShiroUtils.getTenantId());
        collectionNotificationUser.setUpdateUser(ShiroUtils.getUserId());
        collectionNotificationUser.setUpdateTime(new Date());
        collectionNotificationUser.setCreateTime(new Date());
        this.save(collectionNotificationUser);
        //补齐通知人信息
        List<CollectionNotificationReceived> receivedList = req.getCollectionNotificationReceiveds();
        if(CollectionUtils.isNotEmpty(receivedList)){
            ArrayList<CollectionNotificationReceived> arrayList=new ArrayList<>();
            receivedList.forEach(x->{
               CollectionNotificationReceived collectionNotificationReceived = new CollectionNotificationReceived();
                BeanUtils.copyProperties(x,collectionNotificationReceived);
                collectionNotificationReceived.setNotificationUserId(collectionNotificationUser.getId());
                //如果邮箱不为空 肯定是平台外用户
               if(StringUtils.isNotBlank(x.getEmail())){
                   collectionNotificationReceived.setNotificationType(2);
                   collectionNotificationReceived.setEmail(x.getEmail());
                   collectionNotificationReceived.setNotificationUserId(collectionNotificationUser.getId());
                   collectionNotificationReceived.setReceivedId(x.getReceivedId());
                   collectionNotificationReceived.setReceivedName("");
                   collectionNotificationReceived.setUpdateUser(ShiroUtils.getUserId());
                   collectionNotificationReceived.setTenantId(ShiroUtils.getTenantId());
                   collectionNotificationReceived.setCreateUser(ShiroUtils.getUserId());
                   collectionNotificationReceived.setCreateTime(new Date());
                   collectionNotificationReceived.setUpdateTime(new Date());
               }else{
                   SysUserEntity  sysUserEntity = collectionNotificationUserMapper.queryUserByName(x.getReceivedName());
                   if(sysUserEntity==null){
                       throw new RRException("用户邮箱不存在");
                   }
                   collectionNotificationReceived.setNotificationUserId(collectionNotificationUser.getId());
                   collectionNotificationReceived.setEmail(sysUserEntity.getEmail());
                   collectionNotificationReceived.setNotificationType(1);
                   collectionNotificationReceived.setReceivedId(x.getReceivedId());
                   collectionNotificationReceived.setReceivedName(x.getReceivedName());
                   collectionNotificationReceived.setUpdateUser(ShiroUtils.getUserId());
                   collectionNotificationReceived.setTenantId(ShiroUtils.getTenantId());
                   collectionNotificationReceived.setCreateUser(ShiroUtils.getUserId());
                   collectionNotificationReceived.setCreateTime(new Date());
                   collectionNotificationReceived.setUpdateTime(new Date());
               }
                arrayList.add(collectionNotificationReceived);
           });
            CollectionNotificationReceivedServiceImpl.bathSaveCollectionNotificationReceived(arrayList);
        }
    }

    @Override
    @Transactional
    public void upd(CollectionNotificationUser req) {
        checkDate(req,"update");
        CollectionNotificationUser collectionNotificationUser = new CollectionNotificationUser();
        BeanUtils.copyProperties(req,collectionNotificationUser);
        collectionNotificationUser.setUpdateUser(ShiroUtils.getUserId());
        collectionNotificationUser.setUpdateTime(new Date());
        collectionNotificationUser.setTenantId(ShiroUtils.getTenantId());
        this.updateById(collectionNotificationUser);
        //补齐通知人信息
        List<CollectionNotificationReceived> receivedList = req.getCollectionNotificationReceiveds();
        if(CollectionUtils.isNotEmpty(receivedList)){
            ArrayList<CollectionNotificationReceived> arrayList=new ArrayList<>();
            receivedList.forEach(x->{
                CollectionNotificationReceived collectionNotificationReceived = new CollectionNotificationReceived();
                BeanUtils.copyProperties(x,collectionNotificationReceived);
                collectionNotificationReceived.setNotificationUserId(collectionNotificationUser.getId());
                //1为部门用户  2为平台用户
                if(x.getNotificationType()==2){
                    collectionNotificationReceived.setEmail(x.getEmail());
                    collectionNotificationReceived.setNotificationType(2);
                    collectionNotificationReceived.setReceivedId(x.getReceivedId());
                    collectionNotificationReceived.setNotificationUserId(req.getId());
                    collectionNotificationReceived.setReceivedName("");
                    collectionNotificationReceived.setUpdateUser(ShiroUtils.getUserId());
                    collectionNotificationReceived.setUpdateTime(new Date());
                }else{
                    SysUserEntity  sysUserEntity = collectionNotificationUserMapper.queryUserByName(x.getReceivedName());
                    if(sysUserEntity==null){
                        throw new RRException("用户邮箱不存在");
                    }
                    collectionNotificationReceived.setNotificationType(1);
                    collectionNotificationReceived.setEmail(sysUserEntity.getEmail());
                    collectionNotificationReceived.setReceivedId(x.getReceivedId());
                    collectionNotificationReceived.setNotificationUserId(req.getId());
                    collectionNotificationReceived.setReceivedName(x.getReceivedName());
                    collectionNotificationReceived.setUpdateUser(ShiroUtils.getUserId());
                    collectionNotificationReceived.setUpdateTime(new Date());
                }
                arrayList.add(collectionNotificationReceived);
            });
            CollectionNotificationReceivedServiceImpl.bathUpdateCollectionNotificationReceived(arrayList,collectionNotificationUser.getId());
        }
    }

    @Override
    @Transactional
    public void del(Long id) {
        CollectionNotificationUser byId = getById(id);
        Boolean tenantAdminByUserId = sysTenantService.isTenantAdminByUserId(byId.getTenantId(), ShiroUtils.getUserId());
        Long userId = ShiroUtils.getUserId();
        if(!Objects.equals(byId.getCreateUser(),userId)){
            //判断是否租户管理员   租户管理员可以删除
            if(!tenantAdminByUserId){
                throw new RRException("非本人创建的或者非租户管理员,不允许删除");
            }
        }
        this.baseMapper.deleteById(id);
        CollectionNotificationReceivedServiceImpl.delByNotificationUserId(id);
    }



    /**
     * 檢查數據
     * @param req
     * @param type
     */
    public void checkDate(CollectionNotificationUser req,String type){
        if(req.getDescribes()!=null&&req.getDescribes().length()>200){
            throw new RRException("用户通知组描述不能超过200个字符");
        }
        if(req.getUserGroupName()==null){
            throw new RRException("用户组名称不能为空");
        }
        if(!req.getUserGroupName().matches("^[\u4E00-\u9FA5a-zA-Z0-9_]{2,20}$")){
            throw new RRException("中文字母数字下划线组合");
        }
        LambdaQueryWrapper<CollectionNotificationUser> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(CollectionNotificationUser::getUserGroupName,req.getUserGroupName());
        if("save".equals(type)){
            if(this.count(lambdaQuery)>=1){
                throw  new RRException("用户组不能重复");
            }
        }else {
            if(req.getId()==null){
                throw new RRException("id不能为空");
            }
            CollectionNotificationUser byId = getById(req.getId());
            Boolean tenantAdminByUserId = sysTenantService.isTenantAdminByUserId(byId.getTenantId(), ShiroUtils.getUserId());
            Long userId = ShiroUtils.getUserId();
            if(!Objects.equals(byId.getCreateUser(),userId)){
                //判断是否租户管理员   租户管理员可以删除
                if(!tenantAdminByUserId){
                    throw new RRException("非本人创建的或者非租户管理员,不允许编辑");
                }
            }
            lambdaQuery.notIn(CollectionNotificationUser::getUserGroupName,req.getUserGroupName());
            if(this.count(lambdaQuery)>=1){
                throw  new RRException("用户组不能重复");
            }
        }
    }
}
